package com.stp.rabbitmq.controller;

import cn.hutool.core.util.StrUtil;
import com.stp.rabbitmq.config.DeadConfig;
import com.stp.rabbitmq.constant.QueueConstant;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class RabbitmqController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String send(@RequestParam("queue")String queue,
                       @RequestParam("message")String message){

        if(StrUtil.isEmpty(queue)){
            queue = QueueConstant.COMMON_QUEUE;
        }
        rabbitTemplate.convertAndSend(queue,message);
        return "ok";
    }

    @GetMapping("/sendMsg5")
    public String sendMsg5() {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                rabbitTemplate.convertAndSend(DeadConfig.CUSTOM_DELAY_EXCHANGE_NAME, DeadConfig.DEAD_QUEUE_NAME, "测试消息" + i, msg -> {
                    msg.getMessageProperties().setPriority(5);
                    msg.getMessageProperties().setDelay(10000);//延时10描述
                    return msg;
                });
            } else {
                rabbitTemplate.convertAndSend(DeadConfig.DEAD_EXCHANGE_NAME, DeadConfig.DEAD_QUEUE_NAME, "测试消息" + i,msg -> {
                    msg.getMessageProperties().setPriority(5);
                    msg.getMessageProperties().setDelay(1000);//延时10描述
                    return msg;
                });
            }
        }
        return "发送成功";
    }

    @GetMapping("/sendMsg3")
    public String sendMsg3() {
        // 测试正常消息
        CorrelationData correlationData1 = new CorrelationData();
        correlationData1.setId("1");
        rabbitTemplate.convertAndSend(QueueConstant.COMMON_EXCHANGE, QueueConstant.COMMON_QUEUE, "测试消息1", correlationData1);

        // 测试消息无法到交换机
        CorrelationData correlationData2 = new CorrelationData();
        correlationData2.setId("2");
        rabbitTemplate.convertAndSend(QueueConstant.COMMON_EXCHANGE + "1", QueueConstant.COMMON_QUEUE, "测试消息2", correlationData2);

        // 测试消息无法路由到队列
        CorrelationData correlationData3 = new CorrelationData();
        correlationData3.setId("3");
        rabbitTemplate.convertAndSend(QueueConstant.COMMON_EXCHANGE, QueueConstant.COMMON_QUEUE + "1", "测试消息3", correlationData3);

        return "发送成功";
    }
}
